import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
// js向flutter传递数据 - 通过 channel

const String htmlStr = '''
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="utf-8" />
  <title>js通过channel向flutter传递数据</title>
</head>
<body>
  <button id="btn" style="font-size: 2.5em">传递参数</button>
  <script type="text/javascript">
    var btn = document.getElementById("btn");
    btn.addEventListener('click',function(){
      hiPop.postMessage("Hi pop cc");
    },false)
  </script>
</body>
</html>
''';


class Js2flutterByChannel extends StatefulWidget {
  const Js2flutterByChannel({super.key});

  @override
  State<Js2flutterByChannel> createState() => _Js2flutterByChannelState();
}

class _Js2flutterByChannelState extends State<Js2flutterByChannel> {
  late WebViewController controller;

  get _loadBtn => FilledButton(onPressed: (){
    controller.loadHtmlString(htmlStr);// 加载 html 字符串为页面并展示
  }, child: const Text(
    '加载H5页面', style: TextStyle(color: Colors.white),
  ));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('JS向Flutter传递数据channel'),
        actions: [_loadBtn],
      ),
      body: WebViewWidget(controller: controller),
    );
  }

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted)
    ..addJavaScriptChannel('hiPop', onMessageReceived: (JavaScriptMessage jsMsg){
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(jsMsg.message)));
    })
    ;
  }
}
